﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace TaskInWPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("当前线程的ID是：" + threadId);
            AddNum();
        }

        private async static void AddNum()
        {
            Dispatcher.CurrentDispatcher.Invoke(() => { });
           await Dispatcher.CurrentDispatcher.BeginInvoke((Action)delegate ()
            {
                // 在主线程中执行需要操作的UI代码
            });
            await Task.Delay(1000);
            int threadId = Thread.CurrentThread.ManagedThreadId;
            Console.WriteLine("方法中的线程的ID是：" + threadId);
            while (true)
            {
                // 一定要用异步方法！！！！
                //Invoke(new Action(() =>
                //{
                //    textBox1.Text = (++i).ToString();
                //}));
                await Task.Delay(500);
            }
        }
    }
}
